package spring.cloud.study.controller;

import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import spring.cloud.study.entity.base.ResponseModel;


@RestController
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private DiscoveryClient client;
	//@Autowired
	//private Environment env;//获取系统配置环境变量值
	
	@GetMapping("/provider/hello")
	public ResponseModel getServiceInstance() {
		ServiceInstance instance = null;
		try {
			//远程服务线程阻塞（服务端）,Hystrix默认远程调用超过1s线程阻塞。模拟场景也可以发生在消费端
			//int sleepTime = new Random().nextInt(3000);
			//logger.info("sleepTime:" + sleepTime);
			//Thread.sleep(sleepTime);
			
			//int i = 1/0; 
			List<ServiceInstance> instances = client.getInstances("EUREKA-PROVIDER");
			instance = instances.get(0);
			logger.info("{}:{}:{}", instance.getServiceId(), instance.getHost(), instance.getPort());
		} catch (Exception e) {
			return ResponseModel.errorExceptionMsg(e.getMessage());
		}
		return ResponseModel.successMsg("调用：" + instance.getServiceId() + instance.getHost() + instance.getPort() + "成功！");
	}

}
